﻿using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utility1;

namespace eDream.Page
{
    public partial class gio_hang : System.Web.UI.UserControl
    {
        public string pathUrl = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            pathUrl = WebUtils.pathUrl();
            if(!IsPostBack)
            {
                LoadT();
                
                 UserDB user_obj = (UserDB)Session[Global.SESS_USER];
                BuildShop();
                if (user_obj != null)
                {
                    cbxTinh.SelectedIndex = 0;
                    BinInfor(user_obj.ID);
                }
            }
           
        }

        void BuildShop()
        {
            try{
                string id = Request.QueryString["k"].ToString();
                string soluong = "1";
                if (id == "0")
                {
                    pn1.Visible = false;
                    pn2.Visible = false;
                   
                }
                else
                {
                    DataClasses1DataContext dx = new DataClasses1DataContext();
                    try
                    {
                        dx.Connection.Open();
                        try
                        {
          
                            soluong = Request.QueryString["n"];
                        }
                        catch (Exception) { }
                        var list = from k in dx.GetTable<Product_tb>()
                                   where k.ID == int.Parse(id)
                                   select k;
                     
                        IList<ViewCart> viewCart = new List<ViewCart>();
                        if(Session["viewCart"]!=null)
                            viewCart = (List<ViewCart>)Session["viewCart"];

                        foreach (Product_tb p in list)
                        {
                            ViewCart v = new ViewCart();
                            v.ID = p.ID;
                            v.iDongiamoi = p.iDongia;
                            v.image = p.image;
                            v.iProName = p.iProName;
                            v.soluong = int.Parse(soluong);
                            v.tota = int.Parse(soluong) * p.iDongiamoi;
                            viewCart.Add(v);
                            
                            Session["viewCart"] = viewCart;

                            grvCart.DataSource = (List<ViewCart>)Session["viewCart"]; 
                            grvCart.DataBind();

                            CaculatorGrview();
                        }
                    }
                    catch (Exception) { }
                    finally { dx.Connection.Close(); }
                }
            }catch(Exception){}
        }

       

       

       
       
        protected void cbPhuong_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadP();
           
        }

        protected void cbQuan_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadQ();
        }

        void LoadT()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                dx.Connection.Open();
                var list = from k in dx.Thanhphos
                           select k;
                cbxTinh.DataSource = list;
                cbxTinh.ValueField = "ID";
                cbxTinh.TextField = "name";
                cbxTinh.DataBind();

               
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }

        void LoadQ()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                dx.Connection.Open();
                var list = from k in dx.Quan_huyens
                           where k.idTP == int.Parse(cbxTinh.Value.ToString())
                           select new { k.ID, k.name };
                cbQuan.DataSource = list;
                cbQuan.ValueField = "ID";
                cbQuan.TextField = "name";
                cbQuan.DataBind();

                ListEditItem item = new ListEditItem();
                item.Text = "--- Chọn quận/huyện ---";
                item.Value = "0";
                item.Index = 0;
                cbQuan.Items.Insert(0, item);
                cbQuan.SelectedIndex = 0;
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }

        void LoadP()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                dx.Connection.Open();
                var list = from k in dx.phuong_xas
                           where k.idquan == int.Parse(cbQuan.Value.ToString())
                           select new { k.ID, k.name };
                cbPhuong.DataSource = list;
                cbPhuong.ValueField = "ID";
                cbPhuong.TextField = "name";
                cbPhuong.DataBind();
                ListEditItem item = new ListEditItem();
                item.Text = "---Chọn phường/xã---";
                item.Value = "0";
                item.Index = 0;
                cbPhuong.Items.Insert(0, item);

                cbPhuong.SelectedIndex = 0;
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }
        protected void btnOK_Click(object sender, EventArgs e)
        {
            String link = "";
            string id = Request.QueryString["k"].ToString();
            string mauda = timmaUudai();
            if (mauda != "")
            {
                
                string dh = Dathang(mauda);
                string chuoi = updateDH(dh);
                if (rdbGiaotien.Checked == true)
                {
                    link = pathUrl + "/Thank/" + dh + "/Don-hang.html";
                }
                else if (rdbNganluong.Checked == true)
                {
                    link = "https://www.nganluong.vn/button_payment.php?receiver=sipomun@gmail.com&product_name=" + dh + "&price=" + Session["tongtien"].ToString() + "&return_url=http://msmart.vn/Don-hang/" + dh + ".html&comments=Thanh toán đơn hàng trên kênh bán lẽ của Msmart.vn....";
                }
                else if (rdbbaokim.Checked == true)
                    link = "https://www.baokim.vn/payment/product/version11?business=sipomun@gmail.com&product_name=" + dh + "&product_price=" + Session["tongtien"].ToString() + "&product_quantity=" + 1 + "&total_amount=" + Session["tongtien"].ToString() + "&url_detail=http://msmart.vn" + "&url_success=http://msmart.vn/Don-hang/" + dh + "/" + chuoi + ".html&url_cancel=http://msmart.vn/Gio-hang/" + id + "/" + 1 + "/no.html&product_description=Thanh toán đơn hàng trên kênh bán lẽ của Msmart.vn";
                if (dh != "")
                    Response.Redirect(link);
                 
            }
            
        }

        string Dathang(string maudai)
        {
            string hinhthuc="";
            if (rdbGiaotien.Checked == true)
                hinhthuc = "Giao tiền";
            else if (rdbNganluong.Checked == true)
                hinhthuc = "Ngân lượng";
            else if (rdbNganluong.Checked == true)
                hinhthuc = "Bảo kim";
            string MDH = "";

            GridViewDataColumn colImage = grvCart.Columns["image"] as GridViewDataColumn;
            GridViewDataColumn colIproname = grvCart.Columns["iProName"] as GridViewDataColumn;
            GridViewDataColumn col1 = grvCart.Columns["soluong"] as GridViewDataColumn;
            GridViewDataColumn col2 = grvCart.Columns["dongia"] as GridViewDataColumn;
            GridViewDataColumn col3 = grvCart.Columns["tota"] as GridViewDataColumn;

            ASPxLabel lbtota1 = (ASPxLabel)grvCart.FindFooterCellTemplateControl(col3, "lbtota1");
            float tongtong = 0;
            string ArrayID = "";
            for (int i = 0; i < grvCart.VisibleRowCount; i++)
            {

                HiddenField hdfImage = (HiddenField)grvCart.FindRowCellTemplateControl(i, colImage, "hdfImage");
                HiddenField hdfID = (HiddenField)grvCart.FindRowCellTemplateControl(i, colImage, "hdfID");
                ASPxLabel lbsanpham = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, colIproname, "lbsanpham");
                ASPxSpinEdit spin = (ASPxSpinEdit)grvCart.FindRowCellTemplateControl(i, col1, "spSoluong");
                ASPxLabel lbDongia = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, col2, "lbDongia");
                ASPxLabel lbtota = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, col3, "lbtota");

                ArrayID = ArrayID + hdfID.Value.Trim() + ";" + hdfImage.Value.Trim() + ";" + spin.Value.ToString().Trim() + ";" + lbDongia.Text.Replace("đ", "").Replace(",", "") + ":";
                
                float tong = int.Parse(spin.Value.ToString()) * float.Parse(lbDongia.Text.Replace("đ", "").Replace(",", ""));
                tongtong = tongtong + tong;
            }
            try
            {
                int uId = 0;
                string ip = "0";
                UserDB user_obj = (UserDB)Session[Global.SESS_USER];
                if (user_obj != null)
                    uId = user_obj.ID;
                if (uId == 0)
                    ip = Session.SessionID;
                string id = Request.QueryString["k"].ToString();
                Xuly xl = new Xuly();
                SqlParameter[] arrParam =
            {
             new SqlParameter("@UserID", System.Data.SqlDbType.Int),
             new SqlParameter("@IP_ID", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@ArrayID", System.Data.SqlDbType.NVarChar),
           
             new SqlParameter("@flag", System.Data.SqlDbType.Int),
             new SqlParameter("@datePost", System.Data.SqlDbType.DateTime),
             new SqlParameter("@dateUp", System.Data.SqlDbType.DateTime),
          
             new SqlParameter("@thanhtien", System.Data.SqlDbType.Float),
             new SqlParameter("@trangthai", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@ghichu", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@visible", System.Data.SqlDbType.Int),
             new SqlParameter("@hinhthuc", System.Data.SqlDbType.NVarChar),

             new SqlParameter("@Thanhpho", System.Data.SqlDbType.Int),
             new SqlParameter("@Quan", System.Data.SqlDbType.Int),
             new SqlParameter("@phuong", System.Data.SqlDbType.Int),
             new SqlParameter("@duong", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@sonha", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@hovaten", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@dienthoai", System.Data.SqlDbType.NVarChar),
             new SqlParameter("@MaUuDai", System.Data.SqlDbType.NVarChar)
            };
                arrParam[0].Value = uId;
                arrParam[1].Value = ip;
                arrParam[2].Value = ArrayID;
                arrParam[3].Value = 1;
                arrParam[4].Value = DateTime.Now;
                arrParam[5].Value = DateTime.Now;
                arrParam[6].Value = tongtong;
                arrParam[7].Value = "Mới đặt";
                arrParam[8].Value = txtNote.Text;
                arrParam[9].Value = 1;
                arrParam[10].Value = hinhthuc;

                arrParam[11].Value = int.Parse(cbxTinh.Value.ToString());
                arrParam[12].Value = int.Parse(cbQuan.Value.ToString());
                arrParam[13].Value = int.Parse(cbPhuong.Value.ToString());
                arrParam[14].Value = txtDuong.Text.Trim();
                arrParam[15].Value = txtSonha.Text.Trim();
                arrParam[16].Value = txtHoten.Text.Trim();
                arrParam[17].Value = txtDienthoai.Text.Trim();
                arrParam[18].Value = maudai;

                DataTable dt = xl.ExcuteStoreTable("CreateDonhang", arrParam);
                MDH = dt.Rows[0]["code"].ToString();
            }
            catch (Exception) { }
            return MDH;

        }

        string updateDH(string dh)
        {
            string chuoi = "";
            chuoi = Global.ToEncoding(dh, "Ilove-You-Fptasuka89-2013");
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                Don_hang d = dx.Don_hangs.Single(p => p.Ma_DH == dh);
                d.MaEnc = chuoi;
                dx.SubmitChanges();
            }
            catch (Exception) { }
            return chuoi;
        }

        string timmaUudai()
        {
            string ma = "";
            if (txtMa.Text != "")
            {
                
                DataClasses1DataContext dx = new DataClasses1DataContext();
                try
                {
                    dx.Connection.Open();
                    var list = from k in dx.Employees
                               where k.UserName == txtMa.Text.Trim()
                               select k;
                    foreach (Employee e in list)
                        ma = e.UserName;
                    if (ma=="")
                    {
                         ma = "";
                        lbthongbao.Text = "Mã chiết khấu không tồn tại, vui lòng nhập lại mã khác hoặc để trống";
                    }
                }
                catch (Exception)
                {
                   
                }
                finally { dx.Connection.Close(); }
            }
            else
               ma = "A0005";
            return ma;
        }

        void BinInfor(int id)
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                dx.Connection.Open();
                var list = from k in dx.Don_hang_detail_tbs
                           where k.UserID == id
                           orderby k.ID ascending
                           select k;
                foreach (Don_hang_detail_tb dh in list)
                {
                    txtDienthoai.Text = dh.dienthoai;
                    txtDuong.Text = dh.duong;
                    txtHoten.Text = dh.hovaten;
                    txtSonha.Text = dh.sonha;
                    cbxTinh.Items.FindByValue(dh.Thanhpho).Selected = true ;
                    //cbxTinh.Value = dh.Thanhpho;
                    LoadQ();
                    cbQuan.SelectedIndex = cbQuan.Items.FindByValue(dh.Quan).Index;
                    LoadP();
                    cbPhuong.Items.FindByValue(dh.phuong).Selected = true;
                   
                }
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }

       

        protected void ASPxCallbackPanel2_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            CaculatorGrview();
        }

        void CaculatorGrview()
        {
            
            GridViewDataColumn colImage = grvCart.Columns["image"] as GridViewDataColumn;
            GridViewDataColumn colIproname = grvCart.Columns["iProName"] as GridViewDataColumn;
            GridViewDataColumn col1 = grvCart.Columns["soluong"] as GridViewDataColumn;
            GridViewDataColumn col2 = grvCart.Columns["dongia"] as GridViewDataColumn;
            GridViewDataColumn col3 = grvCart.Columns["tota"] as GridViewDataColumn;

            IList<ViewCart> viewCart = new List<ViewCart>();
           /*
            if (Session["viewCart"] != null)
                viewCart = (List<ViewCart_>)Session["viewCart"];
           */
            ASPxLabel lbtota1 = (ASPxLabel)grvCart.FindFooterCellTemplateControl(col3, "lbtota1");
            float tongtong = 0;
            for (int i = 0; i < grvCart.VisibleRowCount; i++)
            {
               
                HiddenField hdfImage = (HiddenField)grvCart.FindRowCellTemplateControl(i, colImage, "hdfImage");
                HiddenField hdfID = (HiddenField)grvCart.FindRowCellTemplateControl(i, colImage, "hdfID");
                ASPxLabel lbsanpham = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, colIproname, "lbsanpham");
                ASPxSpinEdit spin = (ASPxSpinEdit)grvCart.FindRowCellTemplateControl(i, col1, "spSoluong");
                ASPxLabel lbDongia = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, col2, "lbDongia");
                ASPxLabel lbtota = (ASPxLabel)grvCart.FindRowCellTemplateControl(i, col3, "lbtota");
               

                ViewCart v = new ViewCart();
                v.ID = int.Parse(hdfID.Value.ToString());
                v.iDongiamoi = double.Parse(lbDongia.Text.Replace("đ", "").Replace(",", ""));
                v.image = hdfImage.Value;
                v.iProName = lbsanpham.Text;
                v.soluong = int.Parse(spin.Value.ToString());
               // v.tota = int.Parse((spin.Value.ToString()) * p.iDongiamoi;
                viewCart.Add(v);



                lbDongia.Text = String.Format("{0:0,0}đ", double.Parse(lbDongia.Text.Replace("đ", "").Replace(",", "")));
                float tong = int.Parse(spin.Value.ToString()) * float.Parse(lbDongia.Text.Replace("đ", "").Replace(",",""));
                tongtong = tongtong + tong;
                lbtota.Text = String.Format("{0:0,0}đ",tong);
               
                
            }
            lbtota1.Text = String.Format("{0:0,0}đ", tongtong);
            Session["tongtien"] = tongtong;
            Session["viewCart"] = viewCart;
        }

        protected void grvCart_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            object k = e.Keys[0];
            
            IList<ViewCart> viewCart = new List<ViewCart>();
            if (Session["viewCart"] != null)
                viewCart = (List<ViewCart>)Session["viewCart"];

            //var list = (List<ViewCart_>)Session["viewCart"];

            // find the exact item to remove.
            var itemToRemove = viewCart.FirstOrDefault(u => u.ID == int.Parse(k.ToString()));

            // if found, remove it
            if (itemToRemove != null)
            {
                viewCart.Remove(itemToRemove);
            }
            e.Cancel = true;
            Session["viewCart"] = viewCart;
            grvCart.DataSource = (List<ViewCart>)Session["viewCart"];
            grvCart.DataBind();
            //grvCart.DeleteRow();
            
        }

        protected void grvCart_AfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            CaculatorGrview();
        }

       

      

       

      
    }
}